package br.pucrs.lognplay.faces.bean;

import java.util.UUID;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

import br.pucrs.lognplay.entity.Client;
import br.pucrs.lognplay.entity.DynamicView;
import br.pucrs.lognplay.entity.User.Role;
import br.pucrs.lognplay.service.ClientManagementService;

@ManagedBean
@ViewScoped
public class ClientManagementBean extends Bean {

	private Client client;

	@EJB
	private ClientManagementService clientManagementService;

	public Client getClient() {
		try {
			if (client == null) {
				String clientId = getParameterValue("clientId");

				if (clientId == null) {
					Role loggedUserRole = getLoggedUser().getRole();

					if (loggedUserRole.equals(Role.MASTER_USER)) {
						client = new Client(UUID.randomUUID());
						client.setRetentionPeriod(30);
						DynamicView dynamicView = new DynamicView(UUID.randomUUID());
						dynamicView.setName("Dynamic View");
						dynamicView.setDescription("Dynamic View");
						dynamicView.setClient(client);
						client.setDynamicView(dynamicView);
					} else if (loggedUserRole.equals(Role.CLIENT_MASTER_USER)) {
						client = getLoggedUser().getClient();
					}
				} else {
					client = clientManagementService.getClientById(clientId);
				}
			}

			return client;
		} catch (Exception e) {
			throw new BeanException("Unexpected error", e);
		}
	}

	public void setClient(Client client) {
		this.client = client;
	}

	public String save() {
		try {
			clientManagementService.mergeClient(client);
			addInformationMessage("The changes have been saved", null);
			return null;
		} catch (Exception e) {
			throw new BeanException("Unexpected error", e);
		}
	}
}
